#include "game.hpp"
#include <cstdlib>
#include <ctime>

//------------private functions------------
void Game::reserveMemory(){
    pattern = new int[fields];
    reply = new int[fields];
}

void Game::createPattern(){
    srand(time(NULL));

    for(int i = 0; i < fields; i++){
        pattern[i] = rand() % colors;
    }
}

void Game::initGame(){
    round = 0;
    createPattern();

    for(int i = 0; i < fields; i++){
        reply[i] = 0;
    }
}

void Game::createReply(int *ans){
    int itReply = 0;

    for(int i = 0; i < fields; i++){
        if(ans[i] == pattern[i]){
            reply[itReply] = 2;
            itReply++;
        }
        else {
            for(int j = 0; j < fields; j++){
                if(ans[i] == pattern[j]) {
                    reply[itReply] = 1;
                    itReply++;
                    break;
                }
            }
        }
    }
    for(; itReply < fields; itReply++){
        reply[itReply] = 0;
    }
}

//------------public functions------------
Game::Game(int rounds, int fields, int colors): rounds(rounds+1), fields(fields), colors(colors){
    reserveMemory();
    initGame();
}

int* Game::Round(int *ans){
    if( !isEnd() ){
        createReply(ans);
        round++;

        return reply;
    }
    return NULL;
}
int Game::isEnd(){
    if( round == rounds - 1 ) return 2;

    bool end = true;
    for(int i = 0; i < fields; i++){
        if( reply[i] != 2 ) end = false;
    }
    if(end) return 1;

    return 0;
}

void Game::gameReset(){
    initGame();
}

//getters
int Game::getRounds(){
    return rounds;
}

int Game::getFields(){
    return fields;
}

int Game::getColors(){
    return colors;
}

int Game::getRound(){
    return round;
}
